{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "0c266183",
   "metadata": {},
   "source": [
    "# Query Response Evaluator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9080b39e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import logging\n",
    "import sys\n",
    "\n",
    "logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n",
    "logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d0b2364-4806-4656-81e7-3f6e4b910b5b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index import (\n",
    "    TreeIndex,\n",
    "    VectorStoreIndex,\n",
    "    SimpleDirectoryReader,\n",
    "    LLMPredictor,\n",
    "    ServiceContext,\n",
    "    Response,\n",
    ")\n",
    "from llama_index.llms import OpenAI\n",
    "from llama_index.evaluation import QueryResponseEvaluator\n",
    "import pandas as pd\n",
    "\n",
    "pd.set_option(\"display.max_colwidth\", 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9b98f89-d5b8-4d29-92f6-ad76d5060e9f",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# gpt-3 (davinci)\n",
    "gpt3 = OpenAI(temperature=0, model=\"text-davinci-003\")\n",
    "service_context_gpt3 = ServiceContext.from_defaults(llm=gpt3)\n",
    "\n",
    "# gpt-4\n",
    "gpt4 = OpenAI(temperature=0, model=\"gpt-4\")\n",
    "service_context_gpt4 = ServiceContext.from_defaults(llm=gpt4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8eb3e616-64e5-4bf4-a67b-661e9b3657e7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "evaluator = QueryResponseEvaluator(service_context=service_context_gpt3)\n",
    "evaluator_gpt4 = QueryResponseEvaluator(service_context=service_context_gpt4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1298bbb4-c99e-431e-93ef-eb32c0a2fc2a",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "documents = SimpleDirectoryReader(\"../test_wiki/data\").load_data()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dca06a5b-8a15-40b4-8c7f-dae5407c674f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# create tree index\n",
    "tree_index = TreeIndex.from_documents(documents)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41f0e53f-77a6-40d5-94ae-3f81b01af75c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# create vector index\n",
    "vector_index = VectorStoreIndex.from_documents(\n",
    "    documents, service_context=ServiceContext.from_defaults(chunk_size=512)\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "af730b2e-6949-4865-b7af-bb2bc60a9173",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# define jupyter display function\n",
    "def display_eval_df(query: str, response: Response, eval_result: str) -> None:\n",
    "    eval_df = pd.DataFrame(\n",
    "        {\n",
    "            \"Query\": query,\n",
    "            \"Response\": str(response),\n",
    "            \"Source\": response.source_nodes[0].source_text[:1000] + \"...\",\n",
    "            \"Evaluation Result\": eval_result,\n",
    "        },\n",
    "        index=[0],\n",
    "    )\n",
    "    eval_df = eval_df.style.set_properties(\n",
    "        **{\n",
    "            \"inline-size\": \"600px\",\n",
    "            \"overflow-wrap\": \"break-word\",\n",
    "        },\n",
    "        subset=[\"Response\", \"Source\"]\n",
    "    )\n",
    "    display(eval_df)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4780e16a-aa6c-4143-978d-4a93a4357130",
   "metadata": {},
   "source": [
    "### Evaluate Response\n",
    "\n",
    "Evaluate response relative to source nodes as well as query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68c9ebfe-b1b6-4f4e-9278-174346de8c90",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "query_str = \"What battles took place in New York City in the American Revolution?\"\n",
    "query_engine = tree_index.as_query_engine()\n",
    "response_tree = query_engine.query(query_str)\n",
    "eval_result = evaluator_gpt4.evaluate(query_str, response_tree)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "db9d00bc-8428-4a08-b48e-248ad7570923",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style type=\"text/css\">\n",
       "#T_aa49d_row0_col1, #T_aa49d_row0_col2 {\n",
       "  inline-size: 600px;\n",
       "  overflow-wrap: break-word;\n",
       "}\n",
       "</style>\n",
       "<table id=\"T_aa49d\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th class=\"blank level0\" >&nbsp;</th>\n",
       "      <th id=\"T_aa49d_level0_col0\" class=\"col_heading level0 col0\" >Query</th>\n",
       "      <th id=\"T_aa49d_level0_col1\" class=\"col_heading level0 col1\" >Response</th>\n",
       "      <th id=\"T_aa49d_level0_col2\" class=\"col_heading level0 col2\" >Source</th>\n",
       "      <th id=\"T_aa49d_level0_col3\" class=\"col_heading level0 col3\" >Evaluation Result</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th id=\"T_aa49d_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
       "      <td id=\"T_aa49d_row0_col0\" class=\"data row0 col0\" >What battles took place in New York City in the American Revolution?</td>\n",
       "      <td id=\"T_aa49d_row0_col1\" class=\"data row0 col1\" >The Battle of Long Island, the Battle of White Plains, the Battle of Harlem Heights, the Battle of Fort Washington, the Battle of Fort Lee, and the Battle of Yorktown all took place in New York City during the American Revolution. These battles took place in various locations throughout the city, including Battery Weed and Fort Tompkins, Great Kills Park, and Central Park.</td>\n",
       "      <td id=\"T_aa49d_row0_col2\" class=\"data row0 col2\" >in 2015 makes it the highest of any county in the United States and higher than the density of any individual American city.Manhattan is the cultural, administrative, and financial center of New York City and contains the headquarters of many major multinational corporations, the United Nations headquarters, Wall Street, and a number of important universities. The borough of Manhattan is often described as the financial and cultural center of the world.Most of the borough is situated on Manhattan Island, at the mouth of the Hudson River and the East River, and its southern tip, at the confluence of the two rivers, represents the birthplace of New York City itself. Several small islands also compose part of the borough of Manhattan, including Randalls and Wards Islands, and Roosevelt Island in the East River, and Governors Island and Liberty Island to the south in New York Harbor.\n",
       "Manhattan Island is loosely divided into the Lower, Midtown, and Uptown regions. Uptown Manhattan is divide...</td>\n",
       "      <td id=\"T_aa49d_row0_col3\" class=\"data row0 col3\" >NO</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<pandas.io.formats.style.Styler at 0x17d6e8310>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_eval_df(query_str, response_tree, eval_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "180a5d2e-9286-477b-9cd0-a5976d18d845",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "query_str = \"What battles took place in New York City in the American Revolution?\"\n",
    "query_engine = vector_index.as_query_engine()\n",
    "response_vector = query_engine.query(query_str)\n",
    "eval_result = evaluator_gpt4.evaluate(query_str, response_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "c764b8b3-69b1-4ac8-b88b-3f9e204b8bfb",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style type=\"text/css\">\n",
       "#T_36563_row0_col1, #T_36563_row0_col2 {\n",
       "  inline-size: 600px;\n",
       "  overflow-wrap: break-word;\n",
       "}\n",
       "</style>\n",
       "<table id=\"T_36563\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th class=\"blank level0\" >&nbsp;</th>\n",
       "      <th id=\"T_36563_level0_col0\" class=\"col_heading level0 col0\" >Query</th>\n",
       "      <th id=\"T_36563_level0_col1\" class=\"col_heading level0 col1\" >Response</th>\n",
       "      <th id=\"T_36563_level0_col2\" class=\"col_heading level0 col2\" >Source</th>\n",
       "      <th id=\"T_36563_level0_col3\" class=\"col_heading level0 col3\" >Evaluation Result</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th id=\"T_36563_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
       "      <td id=\"T_36563_row0_col0\" class=\"data row0 col0\" >What battles took place in New York City in the American Revolution?</td>\n",
       "      <td id=\"T_36563_row0_col1\" class=\"data row0 col1\" >\n",
       "The Battle of Long Island and the Great Fire of New York.</td>\n",
       "      <td id=\"T_36563_row0_col2\" class=\"data row0 col2\" >at labor. Slavery became integrally tied to New York's economy through the labor of slaves throughout the port, and the banking and shipping industries trading with the American South. During construction in Foley Square in the 1990s, the African Burying Ground was discovered; the cemetery included 10,000 to 20,000 of graves of colonial-era Africans, some enslaved and some free.The 1735 trial and acquittal in Manhattan of John Peter Zenger, who had been accused of seditious libel after criticizing colonial governor William Cosby, helped to establish the freedom of the press in North America. In 1754, Columbia University was founded under charter by King George II as King's College in Lower Manhattan.\n",
       "\n",
       "\n",
       "=== American Revolution ===\n",
       "\n",
       "The Stamp Act Congress met in New York in October 1765, as the Sons of Liberty organization emerged in the city and skirmished over the next ten years with British troops stationed there. The Battle of Long Island, the largest battle of the American Revolutio...</td>\n",
       "      <td id=\"T_36563_row0_col3\" class=\"data row0 col3\" >YES</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<pandas.io.formats.style.Styler at 0x17d6ea8f0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_eval_df(query_str, response_vector, eval_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4fc3f18a-0ef9-453c-acf8-7aedd784cdcf",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_str = \"What are the airports in New York City?\"\n",
    "query_engine = tree_index.as_query_engine()\n",
    "response_tree = query_engine.query(query_str)\n",
    "eval_result = evaluator_gpt4.evaluate(query_str, response_tree)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "a34490f6-7242-4c31-b49e-b2a65d9923ab",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style type=\"text/css\">\n",
       "#T_26784_row0_col1, #T_26784_row0_col2 {\n",
       "  inline-size: 600px;\n",
       "  overflow-wrap: break-word;\n",
       "}\n",
       "</style>\n",
       "<table id=\"T_26784\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th class=\"blank level0\" >&nbsp;</th>\n",
       "      <th id=\"T_26784_level0_col0\" class=\"col_heading level0 col0\" >Query</th>\n",
       "      <th id=\"T_26784_level0_col1\" class=\"col_heading level0 col1\" >Response</th>\n",
       "      <th id=\"T_26784_level0_col2\" class=\"col_heading level0 col2\" >Source</th>\n",
       "      <th id=\"T_26784_level0_col3\" class=\"col_heading level0 col3\" >Evaluation Result</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th id=\"T_26784_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
       "      <td id=\"T_26784_row0_col0\" class=\"data row0 col0\" >What are the airports in New York City?</td>\n",
       "      <td id=\"T_26784_row0_col1\" class=\"data row0 col1\" >The airports in New York City are John F. Kennedy International Airport (JFK), LaGuardia Airport (LGA), and Newark Liberty International Airport (EWR).</td>\n",
       "      <td id=\"T_26784_row0_col2\" class=\"data row0 col2\" >Avenue are also used as metonyms for national industries there: the theater, finance, advertising, and fashion organizations, respectively.\n",
       "New York City also has an extensive web of freeways and parkways, which link the city's boroughs to each other and to North Jersey, Westchester County, Long Island, and southwestern Connecticut through various bridges and tunnels. Because these highways serve millions of outer borough and suburban residents who commute into Manhattan, it is quite common for motorists to be stranded for hours in traffic congestion that are a daily occurrence, particularly during rush hour. Congestion pricing in New York City will go into effect in 2022 at the earliest.New York City is also known for its rules regarding turning at red lights. Unlike the rest of the United States, New York State prohibits right or left turns on red in cities with a population greater than one million, to reduce traffic collisions and increase pedestrian safety. In New York City, there...</td>\n",
       "      <td id=\"T_26784_row0_col3\" class=\"data row0 col3\" >NO</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<pandas.io.formats.style.Styler at 0x17d52a560>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_eval_df(query_str, response_tree, eval_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97f3ddf1-8dc2-4fb8-831f-2c06649e0955",
   "metadata": {},
   "outputs": [],
   "source": [
    "query_str = \"What are the airports in New York City?\"\n",
    "query_engine = vector_index.as_query_engine()\n",
    "response_vector = query_engine.query(query_str)\n",
    "eval_result = evaluator_gpt4.evaluate(query_str, response_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "01c53014-82b0-4865-b849-c0beb042143d",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style type=\"text/css\">\n",
       "#T_920be_row0_col1, #T_920be_row0_col2 {\n",
       "  inline-size: 600px;\n",
       "  overflow-wrap: break-word;\n",
       "}\n",
       "</style>\n",
       "<table id=\"T_920be\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th class=\"blank level0\" >&nbsp;</th>\n",
       "      <th id=\"T_920be_level0_col0\" class=\"col_heading level0 col0\" >Query</th>\n",
       "      <th id=\"T_920be_level0_col1\" class=\"col_heading level0 col1\" >Response</th>\n",
       "      <th id=\"T_920be_level0_col2\" class=\"col_heading level0 col2\" >Source</th>\n",
       "      <th id=\"T_920be_level0_col3\" class=\"col_heading level0 col3\" >Evaluation Result</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th id=\"T_920be_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
       "      <td id=\"T_920be_row0_col0\" class=\"data row0 col0\" >What are the airports in New York City?</td>\n",
       "      <td id=\"T_920be_row0_col1\" class=\"data row0 col1\" >\n",
       "The airports in New York City are Long Island MacArthur Airport, Trenton–Mercer Airport, Westchester County Airport, and Teterboro Airport.</td>\n",
       "      <td id=\"T_920be_row0_col2\" class=\"data row0 col2\" >announced in July 2015 to entirely rebuild LaGuardia Airport in a multibillion-dollar project to replace its aging facilities. Other commercial airports in or serving the New York metropolitan area include Long Island MacArthur Airport, Trenton–Mercer Airport and Westchester County Airport. The primary general aviation airport serving the area is Teterboro Airport.\n",
       "\n",
       "\n",
       "=== Ferries ===\n",
       "\n",
       "The Staten Island Ferry is the world's busiest ferry route, carrying more than 23 million passengers from July 2015 through June 2016 on the 5.2-mile (8.4 km) route between Staten Island and Lower Manhattan and running 24 hours a day. Other ferry systems shuttle commuters between Manhattan and other locales within the city and the metropolitan area.\n",
       "NYC Ferry, a NYCEDC initiative with routes planned to travel to all five boroughs, was launched in 2017, with second graders choosing the names of the ferries. Meanwhile, Seastreak ferry announced construction of a 600-passenger high-speed luxury ferry in Septe...</td>\n",
       "      <td id=\"T_920be_row0_col3\" class=\"data row0 col3\" >NO</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<pandas.io.formats.style.Styler at 0x17d52aa10>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_eval_df(query_str, response_vector, eval_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b860691-9f6a-4b2f-bfef-5a5a56693a18",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "query_str = \"Who is the mayor of New York City?\"\n",
    "query_engine = vector_index.as_query_engine()\n",
    "response_vector = query_engine.query(query_str)\n",
    "eval_result = evaluator_gpt4.evaluate(query_str, response_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "91cce4e3-b4e5-4583-9543-6c3726c0e7d3",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style type=\"text/css\">\n",
       "#T_efae7_row0_col1, #T_efae7_row0_col2 {\n",
       "  inline-size: 600px;\n",
       "  overflow-wrap: break-word;\n",
       "}\n",
       "</style>\n",
       "<table id=\"T_efae7\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th class=\"blank level0\" >&nbsp;</th>\n",
       "      <th id=\"T_efae7_level0_col0\" class=\"col_heading level0 col0\" >Query</th>\n",
       "      <th id=\"T_efae7_level0_col1\" class=\"col_heading level0 col1\" >Response</th>\n",
       "      <th id=\"T_efae7_level0_col2\" class=\"col_heading level0 col2\" >Source</th>\n",
       "      <th id=\"T_efae7_level0_col3\" class=\"col_heading level0 col3\" >Evaluation Result</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th id=\"T_efae7_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
       "      <td id=\"T_efae7_row0_col0\" class=\"data row0 col0\" >Who is the mayor of New York City?</td>\n",
       "      <td id=\"T_efae7_row0_col1\" class=\"data row0 col1\" >\n",
       "The mayor of New York City is Eric Adams.</td>\n",
       "      <td id=\"T_efae7_row0_col2\" class=\"data row0 col2\" >by geographic population boundaries. Each term for the mayor and council members lasts four years and has a two consecutive-term limit, which is reset after a four-year break. The New York City Administrative Code, the New York City Rules, and the City Record are the code of local laws, compilation of regulations, and official journal, respectively.Each borough is coextensive with a judicial district of the state Unified Court System, of which the Criminal Court and the Civil Court are the local courts, while the New York Supreme Court conducts major trials and appeals. Manhattan hosts the First Department of the Supreme Court, Appellate Division while Brooklyn hosts the Second Department. There are also several extrajudicial administrative courts, which are executive agencies and not part of the state Unified Court System.\n",
       "Uniquely among major American cities, New York is divided between, and is host to the main branches of, two different U.S. district courts: the District Court for t...</td>\n",
       "      <td id=\"T_efae7_row0_col3\" class=\"data row0 col3\" >YES</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<pandas.io.formats.style.Styler at 0x17d551090>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_eval_df(query_str, response_vector, eval_result)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "0ee6a336-8fd0-46b3-bb8f-7f47a8781c60",
   "metadata": {
    "tags": []
   },
   "source": [
    "### Evaluate Source Nodes\n",
    "\n",
    "Evaluate the set of returned sources, and determine which sources actually contain the answer to a given query."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "74eed7ba-7ed5-44fa-af4d-356f6ce3b710",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from typing import List\n",
    "\n",
    "# define jupyter display function\n",
    "def display_eval_sources(\n",
    "    query: str, response: Response, eval_result: List[str]\n",
    ") -> None:\n",
    "\n",
    "    sources = [s.node.get_text() for s in response.source_nodes]\n",
    "    eval_df = pd.DataFrame(\n",
    "        {\n",
    "            \"Source\": sources,\n",
    "            \"Eval Result\": eval_result,\n",
    "        },\n",
    "    )\n",
    "    eval_df.style.set_caption(query)\n",
    "    eval_df = eval_df.style.set_properties(\n",
    "        **{\n",
    "            \"inline-size\": \"600px\",\n",
    "            \"overflow-wrap\": \"break-word\",\n",
    "        },\n",
    "        subset=[\"Source\"]\n",
    "    )\n",
    "\n",
    "    display(eval_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e3674ed-2632-4f48-9102-895fea94e340",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# NOTE: you can set response_mode=\"no_text\" to get just the sources\n",
    "query_str = \"What are the airports in New York City?\"\n",
    "query_engine = vector_index.as_query_engine()\n",
    "response_vector = query_engine.query(\n",
    "    query_str, similarity_top_k=3, response_mode=\"no_text\"\n",
    ")\n",
    "eval_source_result = evaluator_gpt4.evaluate_source_nodes(query_str, response_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "35125a2d-927e-40d3-ac83-da9297b6e81e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style type=\"text/css\">\n",
       "#T_62aff_row0_col0, #T_62aff_row1_col0, #T_62aff_row2_col0 {\n",
       "  inline-size: 600px;\n",
       "  overflow-wrap: break-word;\n",
       "}\n",
       "</style>\n",
       "<table id=\"T_62aff\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th class=\"blank level0\" >&nbsp;</th>\n",
       "      <th id=\"T_62aff_level0_col0\" class=\"col_heading level0 col0\" >Source</th>\n",
       "      <th id=\"T_62aff_level0_col1\" class=\"col_heading level0 col1\" >Eval Result</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th id=\"T_62aff_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
       "      <td id=\"T_62aff_row0_col0\" class=\"data row0 col0\" >announced in July 2015 to entirely rebuild LaGuardia Airport in a multibillion-dollar project to replace its aging facilities. Other commercial airports in or serving the New York metropolitan area include Long Island MacArthur Airport, Trenton–Mercer Airport and Westchester County Airport. The primary general aviation airport serving the area is Teterboro Airport.\n",
       "\n",
       "\n",
       "=== Ferries ===\n",
       "\n",
       "The Staten Island Ferry is the world's busiest ferry route, carrying more than 23 million passengers from July 2015 through June 2016 on the 5.2-mile (8.4 km) route between Staten Island and Lower Manhattan and running 24 hours a day. Other ferry systems shuttle commuters between Manhattan and other locales within the city and the metropolitan area.\n",
       "NYC Ferry, a NYCEDC initiative with routes planned to travel to all five boroughs, was launched in 2017, with second graders choosing the names of the ferries. Meanwhile, Seastreak ferry announced construction of a 600-passenger high-speed luxury ferry in September 2016, to shuttle riders between the Jersey Shore and Manhattan, anticipated to start service in 2017; this would be the largest vessel in its class.\n",
       "\n",
       "\n",
       "=== Taxis, vehicles for hire, and trams ===\n",
       "\n",
       "Other features of the city's transportation infrastructure encompass 13,587 yellow taxicabs; other vehicle for hire companies; and the Roosevelt Island Tramway, an aerial tramway that transports commuters between Roosevelt Island and Manhattan Island.\n",
       "\n",
       "\n",
       "=== Streets and highways ===\n",
       "\n",
       "Despite New York's heavy reliance on its vast public transit system, streets are a defining feature of the city. The Commissioners' Plan of 1811 greatly influenced the city's physical development. Several of the city's streets and avenues, including Broadway, Wall Street, Madison Avenue, and Seventh Avenue are also used as metonyms for national industries there: the theater, finance, advertising, and fashion organizations, respectively.\n",
       "New York City also has an extensive web of freeways and parkways, which link the city's boroughs to each other and to North Jersey,</td>\n",
       "      <td id=\"T_62aff_row0_col1\" class=\"data row0 col1\" >YES</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th id=\"T_62aff_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",
       "      <td id=\"T_62aff_row1_col0\" class=\"data row1 col0\" >the Chicago \"L\", the PATCO Speedline serving Philadelphia, and the Copenhagen Metro).\n",
       "Multibillion-dollar heavy rail transit projects under construction in New York City include the Second Avenue Subway, and the East Side Access project.\n",
       "\n",
       "\n",
       "==== Buses ====\n",
       "\n",
       "New York City's public bus fleet runs 24/7 and is the largest in North America. The Port Authority Bus Terminal, the main intercity bus terminal of the city, serves 7,000 buses and 200,000 commuters daily, making it the busiest bus station in the world.\n",
       "\n",
       "\n",
       "=== Air ===\n",
       "\n",
       "New York's airspace is the busiest in the United States and one of the world's busiest air transportation corridors. The three busiest airports in the New York metropolitan area include John F. Kennedy International Airport, Newark Liberty International Airport, and LaGuardia Airport; 130.5 million travelers used these three airports in 2016. JFK and Newark Liberty were the busiest and fourth busiest U.S. gateways for international air passengers, respectively, in 2012; as of 2011, JFK was the busiest airport for international passengers in North America.Plans have advanced to expand passenger volume at a fourth airport, Stewart International Airport near Newburgh, New York, by the Port Authority of New York and New Jersey. Plans were announced in July 2015 to entirely rebuild LaGuardia Airport in a multibillion-dollar project to replace its aging facilities. Other commercial airports in or serving the New York metropolitan area include Long Island MacArthur Airport, Trenton–Mercer Airport and Westchester County Airport. The primary general aviation airport serving the area is Teterboro Airport.\n",
       "\n",
       "\n",
       "=== Ferries ===\n",
       "\n",
       "The Staten Island Ferry is the world's busiest ferry route, carrying more than 23 million passengers from July 2015 through June 2016 on the 5.2-mile (8.4 km) route between Staten Island and Lower Manhattan and running 24 hours a day. Other ferry systems shuttle commuters between Manhattan and other locales within the city and the metropolitan area.\n",
       "NYC Ferry, a NYCEDC initiative with routes planned to travel</td>\n",
       "      <td id=\"T_62aff_row1_col1\" class=\"data row1 col1\" >YES</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th id=\"T_62aff_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",
       "      <td id=\"T_62aff_row2_col0\" class=\"data row2 col0\" >and New Jersey Transit. The combined systems converge at Grand Central Terminal and Pennsylvania Station and contain more than 250 stations and 20 rail lines. In Queens, the elevated AirTrain people mover system connects 24 hours a day JFK International Airport to the New York City Subway and the Long Island Rail Road; a separate AirTrain system is planned alongside the Grand Central Parkway to connect LaGuardia Airport to these transit systems. For inter-city rail, New York City is served by Amtrak, whose busiest station by a significant margin is Pennsylvania Station on the West Side of Manhattan, from which Amtrak provides connections to Boston, Philadelphia, and Washington, D.C. along the Northeast Corridor, and long-distance train service to other North American cities.The Staten Island Railway rapid transit system solely serves Staten Island, operating 24 hours a day. The Port Authority Trans-Hudson (PATH train) links Midtown and Lower Manhattan to northeastern New Jersey, primarily Hoboken, Jersey City, and Newark. Like the New York City Subway, the PATH operates 24 hours a day; meaning three of the six rapid transit systems in the world which operate on 24-hour schedules are wholly or partly in New York (the others are a portion of the Chicago \"L\", the PATCO Speedline serving Philadelphia, and the Copenhagen Metro).\n",
       "Multibillion-dollar heavy rail transit projects under construction in New York City include the Second Avenue Subway, and the East Side Access project.\n",
       "\n",
       "\n",
       "==== Buses ====\n",
       "\n",
       "New York City's public bus fleet runs 24/7 and is the largest in North America. The Port Authority Bus Terminal, the main intercity bus terminal of the city, serves 7,000 buses and 200,000 commuters daily, making it the busiest bus station in the world.\n",
       "\n",
       "\n",
       "=== Air ===\n",
       "\n",
       "New York's airspace is the busiest in the United States and one of the world's busiest air transportation corridors. The three busiest airports in the New York metropolitan area include John F. Kennedy International Airport, Newark Liberty International Airport, and LaGuardia Airport;</td>\n",
       "      <td id=\"T_62aff_row2_col1\" class=\"data row2 col1\" >YES</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<pandas.io.formats.style.Styler at 0x17d6ea6e0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_eval_sources(query_str, response_vector, eval_source_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cdc340a9-1853-414e-9e87-820aa5d82db7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# NOTE: you can set response_mode=\"no_text\" to get just the sources\n",
    "query_str = \"Who is the mayor of New York City?\"\n",
    "query_engine = vector_index.as_query_engine()\n",
    "response_vector = query_engine.query(\n",
    "    query_str, similarity_top_k=3, response_mode=\"no_text\"\n",
    ")\n",
    "eval_source_result = evaluator_gpt4.evaluate_source_nodes(query_str, response_vector)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "b88eb350-cae6-4890-9b55-cb5f750afa9e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style type=\"text/css\">\n",
       "#T_79b25_row0_col0, #T_79b25_row1_col0, #T_79b25_row2_col0 {\n",
       "  inline-size: 600px;\n",
       "  overflow-wrap: break-word;\n",
       "}\n",
       "</style>\n",
       "<table id=\"T_79b25\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th class=\"blank level0\" >&nbsp;</th>\n",
       "      <th id=\"T_79b25_level0_col0\" class=\"col_heading level0 col0\" >Source</th>\n",
       "      <th id=\"T_79b25_level0_col1\" class=\"col_heading level0 col1\" >Eval Result</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th id=\"T_79b25_level0_row0\" class=\"row_heading level0 row0\" >0</th>\n",
       "      <td id=\"T_79b25_row0_col0\" class=\"data row0 col0\" >by geographic population boundaries. Each term for the mayor and council members lasts four years and has a two consecutive-term limit, which is reset after a four-year break. The New York City Administrative Code, the New York City Rules, and the City Record are the code of local laws, compilation of regulations, and official journal, respectively.Each borough is coextensive with a judicial district of the state Unified Court System, of which the Criminal Court and the Civil Court are the local courts, while the New York Supreme Court conducts major trials and appeals. Manhattan hosts the First Department of the Supreme Court, Appellate Division while Brooklyn hosts the Second Department. There are also several extrajudicial administrative courts, which are executive agencies and not part of the state Unified Court System.\n",
       "Uniquely among major American cities, New York is divided between, and is host to the main branches of, two different U.S. district courts: the District Court for the Southern District of New York, whose main courthouse is on Foley Square near City Hall in Manhattan and whose jurisdiction includes Manhattan and the Bronx; and the District Court for the Eastern District of New York, whose main courthouse is in Brooklyn and whose jurisdiction includes Brooklyn, Queens, and Staten Island. The U.S. Court of Appeals for the Second Circuit and U.S. Court of International Trade are also based in New York, also on Foley Square in Manhattan.\n",
       "\n",
       "\n",
       "=== Politics ===\n",
       "The present mayor is Eric Adams. He was elected in 2021 with 67% of the vote, and assumed office on January 1, 2022.\n",
       "The Democratic Party holds the majority of public offices. As of April 2016, 69% of registered voters in the city are Democrats and 10% are Republicans. New York City has not been carried by a Republican  presidential election since President Calvin Coolidge won the five boroughs in 1924. A Republican candidate for statewide office has not won all five boroughs of the city since it was incorporated in 1898. In 2012, Democrat Barack Obama became the first presidential candidate of any party to receive more than 80% of the overall vote in New York City, sweeping all</td>\n",
       "      <td id=\"T_79b25_row0_col1\" class=\"data row0 col1\" >NO</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th id=\"T_79b25_level0_row1\" class=\"row_heading level0 row1\" >1</th>\n",
       "      <td id=\"T_79b25_row1_col0\" class=\"data row1 col0\" >for the Second Circuit and U.S. Court of International Trade are also based in New York, also on Foley Square in Manhattan.\n",
       "\n",
       "\n",
       "=== Politics ===\n",
       "The present mayor is Eric Adams. He was elected in 2021 with 67% of the vote, and assumed office on January 1, 2022.\n",
       "The Democratic Party holds the majority of public offices. As of April 2016, 69% of registered voters in the city are Democrats and 10% are Republicans. New York City has not been carried by a Republican  presidential election since President Calvin Coolidge won the five boroughs in 1924. A Republican candidate for statewide office has not won all five boroughs of the city since it was incorporated in 1898. In 2012, Democrat Barack Obama became the first presidential candidate of any party to receive more than 80% of the overall vote in New York City, sweeping all five boroughs. Party platforms center on affordable housing, education, and economic development, and labor politics are of importance in the city. Thirteen out of 27 U.S. congressional districts in the state of New York include portions of New York City.New York is one of the most important sources of political fundraising in the United States. At least four of the top five ZIP Codes in the nation for political contributions were in Manhattan for the 2004, 2006, and 2008 elections. The top ZIP Code, 10021 on the Upper East Side, generated the most money for the 2004 presidential campaigns of George W. Bush and John Kerry. The city has a strong imbalance of payments with the national and state governments. It receives 83 cents in services for every $1 it sends to the federal government in taxes (or annually sends $11.4 billion more than it receives back). City residents and businesses also sent an additional $4.1 billion in the 2009–2010 fiscal year to the state of New York than the city received in return.\n",
       "\n",
       "\n",
       "== Transportation ==\n",
       "\n",
       "New York City's comprehensive transportation system is both complex and extensive.\n",
       "\n",
       "\n",
       "=== Rapid transit ===\n",
       "Mass transit in New York City, most of which runs 24 hours a day, accounts for one in every three users of mass transit in</td>\n",
       "      <td id=\"T_79b25_row1_col1\" class=\"data row1 col1\" >YES</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th id=\"T_79b25_level0_row2\" class=\"row_heading level0 row2\" >2</th>\n",
       "      <td id=\"T_79b25_row2_col0\" class=\"data row2 col0\" >ed.). New York: The New Press. ISBN 978-1-56584-321-9.\n",
       "Holli, Melvin G., and Jones, Peter d'A., eds. Biographical Dictionary of American Mayors, 1820-1980 (Greenwood Press, 1981) short scholarly biographies each of the city's mayors 1820 to 1980. online; see index at p. 410 for list.Jackson, Kenneth T., ed. (1995). The Encyclopedia of New York City. New Haven: Yale University Press. ISBN 0300055366.\n",
       "Jackson, Kenneth T.; Dunbar, David S., eds. (2005). Empire City: New York Through the Centuries. Columbia University Press. ISBN 978-0-231-10909-3.\n",
       "Lankevich, George L. (1998). American Metropolis: A History of New York City. NYU Press. ISBN 978-0-8147-5186-2.\n",
       "White, E.B. (1949). Here is New York (2000 reissue ed.). Little Bookroom.\n",
       "White, Norval & Willensky, Elliot (2000). AIA Guide to New York City (4th ed.). New York: Three Rivers Press. ISBN 978-0-8129-3107-5.\n",
       "Whitehead, Colson (2003). The Colossus of New York: A City in 13 Parts. New York: Doubleday. ISBN 978-0-385-50794-3.\n",
       "\n",
       "\n",
       "== External links ==\n",
       "\n",
       "Official website \n",
       "NYC Go, official tourism website\n",
       "New York City at Curlie\n",
       " Geographic data related to New York City at OpenStreetMap\n",
       "Collections, 145,000 NYC photographs at the Museum of the City of New York\n",
       "\"The New New York Skyline (interactive)\". National Geographic. November 2015.</td>\n",
       "      <td id=\"T_79b25_row2_col1\" class=\"data row2 col1\" >NO</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<pandas.io.formats.style.Styler at 0x17d6eab00>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "display_eval_sources(query_str, response_vector, eval_source_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72681384-c71d-44b9-9385-54820db30988",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama_index",
   "language": "python",
   "name": "llama_index"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
